import { createSlice } from "@reduxjs/toolkit"
import { setToken, getToken, removeToken } from "@/utils/main.js"
import { postLogin, getUserInfo } from "@/api/user.js"

const userSplice = createSlice({
    name: "user",
    initialState: {
        token: getToken() || "",
        userInfo: {}
    },
    reducers: {
        setTokenKey: (state, action) => {
            state.token = action.payload
            // 持久化token
            setToken(action.payload)
        },
        setUserInfo: (state, action) => {
            state.userInfo = action.payload
        },
        clearUserInfo: (state) => {
            state.token = ""
            state.userInfo = {}
            removeToken()
        }
    }
})

// 获取token
export const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        const res = await postLogin(loginForm)
        // 提交action
        dispatch(setTokenKey(res.data.data.token))
    }
}

// 获取用户个人信息
export const fetchUserInfo = () => {
    return async (dispatch) => {
        const res = await getUserInfo()
        // 提交action
        dispatch(setUserInfo(res.data.data))
    }
}

export const { setTokenKey, setUserInfo, clearUserInfo } = userSplice.actions

export default userSplice.reducer